﻿function getNotificationsCount() {
    $.post("/Users/NotificationsCount")
        .done(function (data) {
            if (data > 0) {
                $("#notificacion-icon").addClass('notification-active');
            }
            else {
                $("#notificacion-icon").removeClass('notification-active');
            }
        })
        .always(function () {
            setTimeout(getNotificationsCount, 30000);
        });
}

$(document).ready(function () {
    if ($("#notificacion-icon").length) {
        getNotificationsCount();
        $("#grid-notifications").bootgrid({
            ajax: true,
            url: urlNotifications,
            formatters: {
                "link": function (column, row) {
                    return '<div class="row"><div class="col-md-7">' + row.Date + '<br/><p class="notification-detail">' + row.Detail + '</p></div><div class="col-md-5"><button class="remove-notification btn btn-default pull-right" data-url="' + row.RemoveUrl + '"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Eliminar</button><a class="btn btn-default pull-right" href="' + row.Url + '" role="button"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> Ver</a>  </div>';
                }
            },
            labels: {
                noResults: "Ninguna notificación encontrada",
                infos: "{{ctx.start}} al {{ctx.end}} de {{ctx.total}} elemento(s)",
                loading: "Cargando",
                refresh: "Actualizar",
                search: "Buscar"
            },
            columnSelection: false,
            rowCount: 5,
            navigation: 2
        }).on("loaded.rs.jquery.bootgrid", function (e) {
            $('.remove-notification').bind('click', function () {
                $.post($(this).data('url'))
                    .done(function (data) {
                        if (data == 'Success') {
                            $("#grid-notifications").bootgrid("reload", true);
                        }
                        else {
                            alert('No se pudó eliminar la notificación.')
                        }
                });
            });
        });
        $('#notificacion-icon').bind('click', function () {
            $("#grid-notifications").bootgrid("reload");
        });
        $('#close-notifications').bind('click', function () {
            $.post("/Notifications/ReadAll").always(function (data) {
                if (data === 'Success') {
                    $("#notificacion-icon").removeClass('notification-active');
                }
                else {
                    $("#notificacion-icon").addClass('notification-active');
                }
            });
        });
    }
});